import cv2
import base64
import numpy as np
from PIL import Image
from aip import AipFace
import re
from io import BytesIO
import types

def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()


def MatrixToImage(data):
    data = data * 255
    new_im = Image.fromarray(data.astype(np.uint8))
    return new_im


def image_to_base64(img):
    output_buffer = BytesIO()
    img.save(output_buffer, format='JPEG')
    byte_data = output_buffer.getvalue()
    base64_str = str(base64.b64encode(byte_data), 'utf-8')
    return base64_str


def skimage2opencv(src):
    src *= 255
    src.astype(int)
    cv2.cvtColor(src, cv2.COLOR_RGB2BGR)
    return src


def opencv2image(src):
    myimage = Image.fromarray(cv2.cvtColor(src, cv2.COLOR_BGR2RGB))
    return myimage


def base64_to_image(base64_str, image_path=None):
    base64_data = re.sub('^data:image/.+;base64,', '', base64_str)
    byte_data = base64.b64decode(base64_data)
    image_data = BytesIO(byte_data)
    img = Image.open(image_data)
    if image_path:
        img.save(image_path)
    return img


faceCascade = cv2.CascadeClassifier('Cascades/haarcascade_frontalface_default.xml')
""" 你的 APPID AK SK """
APP_ID = '10161362'
API_KEY = 'aiZvz15MeM2ot7xaPO5o7iiA'
SECRET_KEY = 'yKWBa3DGpxNcZ4XZx39VcFDzpGNKRVYF'

client = AipFace(APP_ID, API_KEY, SECRET_KEY)
cap = cv2.VideoCapture(0)
cap.set(3, 640)  # set Width
cap.set(4, 480)  # set Height

while True:
    ret, img = cap.read()
    img2 = img
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.2,
        minNeighbors=5,
        minSize=(20, 20)
    )
    if len(faces) > 0:
        print("发现{0}个人脸!".format(len(faces)))
    for (x, y, w, h) in faces:

        cv2.rectangle(img2, (x, y), (x + w, y + h), (255, 0, 0), 2)
        roi_gray = gray[y:y + h, x:x + w]
        roi_color = img[y:y + h, x:x + w]

    #cv2.imshow('video', img)
    cv2.imshow('video', img2)
    k = cv2.waitKey(30) & 0xff
    if k == 27:  # press 'ESC' to quit
        break
    elif k == ord("f") and len(faces) > 0:
        print('远程识别中！')
        pilimage = opencv2image(img)
        image = image_to_base64(pilimage)
        print(image)
        imageType = "BASE64"
        groupIdList = "group1"
        result =client.search(image, imageType, groupIdList);
        if 'error_code' in result and result['error_code']==0:
            faceresult=result['result']
            user_list=faceresult['user_list']
            user=user_list[0]
            print("检测到用户为:"+user['user_id']+' 相似度为'+str(user['score']));
        break
cap.release()
cv2.destroyAllWindows()
